# -*- coding: utf-8 -*-
"""Extensions module. Each extension is initialized in the app factory located in app.py."""
from flask_bcrypt import Bcrypt
from flask_caching import Cache
from flask_debugtoolbar import DebugToolbarExtension
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_static_digest import FlaskStaticDigest
from flask_wtf.csrf import CSRFProtect

bcrypt = Bcrypt()
csrf_protect = CSRFProtect()
login_manager = LoginManager()
db = SQLAlchemy()
migrate = Migrate()
cache = Cache()
debug_toolbar = DebugToolbarExtension()
flask_static_digest = FlaskStaticDigest()



# 导入所需的库
import os
from openai import OpenAI

# 定义OpenAIClient类
class OpenAIClient:
    def __init__(self, model="gpt-3.5-turbo-instruct", max_tokens=1000):
        # 尝试从环境变量中获取OpenAI API密钥
        api_key = os.getenv("OPENAI_API_KEY")
        # 如果没有找到API密钥，抛出异常
        if not api_key:
            raise ValueError("OPENAI_API_KEY环境变量没有设置")
        
        # 设置模型和最大令牌数
        self.model = model
        self.max_tokens = max_tokens
        # 使用API密钥初始化OpenAI客户端
        self.client = OpenAI(api_key=api_key)

    def ask(self, question):
        # 尝试向OpenAI发送问题并获取回答
        try:
            response = self.client.completions.create(
                model=self.model,  # 使用初始化时指定的模型
                prompt=question,  # 将用户问题作为提示
                max_tokens=self.max_tokens  # 使用初始化时指定的最大令牌数
            )
            # 返回回答文本
            return response.choices[0].text
        except Exception as e:
            # 如果请求过程中出现异常，打印错误信息并返回None
            print(f"提问出错: {e}")
            return None

# 创建OpenAIClient实例
openai_client = OpenAIClient()

# 使用示例
# 假设有一个问题"Who won the world series in 2020?"
# question = "谁获得的2020世界杯?"
# answer = openai_client.ask(question)

# if answer:
#     print(f"Answer: {answer}")
# else:
#     print("Failed to get an answer from OpenAI.")


# chat
class OpenAIChatClient:
    def __init__(self):
        """初始化对话历史。"""
        self.messages = [{"role": "system", "content": "你是一个有帮助的助手。"}]

    def ask(self, question):
        """向客户端提问，并返回回答及对话历史。"""
        self.client = OpenAI()
        self.messages.append({"role": "user", "content": question})
        try:
            response = self.client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=self.messages
            )
            answer = response.choices[0].message.content
            self.messages.append({"role": "assistant", "content": answer})
        except Exception as e:
            answer = "抱歉，无法获取回答。"
            print(f"API调用异常：{e}")
        # 返回除系统消息外的所有对话历史
        user_and_assistant_messages = [msg for msg in self.messages if msg["role"] in ["user", "assistant"]]
        return answer, user_and_assistant_messages

openai_chat_client = OpenAIChatClient()
